<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="108px">
      <el-form-item label="申请单号" prop="applyId">
        <el-input
          v-model="queryParams.applyId"
          placeholder="请输入申请单号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="经办人" prop="workStaffName">
        <el-input
          v-model="queryParams.workStaffName"
          placeholder="请输入经办人"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <!--按钮模块-->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="postList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="序号" align="center" type="index"/>
      <el-table-column label="申请单号" align="center" prop="applyId"/>
      <el-table-column label="审核状态" align="center" prop="auditStatus">
        <template slot-scope="scope">
          <span v-if="scope.row.auditStatus==2" style="color: red">已驳回</span>
          <span v-if="scope.row.auditStatus==1" style="color: red">审核通过</span>
          <span v-if="scope.row.auditStatus==0" style="color: red">待审核</span>
        </template>
      </el-table-column>
      <el-table-column label="经办人" align="center" prop="workStaffName"/>
      <el-table-column label="经办人电话" align="center" prop="workTel"/>
      <!--      <el-table-column label="下级审核人" align="center" prop="nextAudit"/>-->
      <el-table-column label="车间主任" align="center" prop="workLeaderName"/>
      <el-table-column label="科室分管人员" align="center" prop="deptStaffName"/>
      <el-table-column label="科室负责人" align="center" prop="deptLeaderName"/>
      <el-table-column label="分管领导" align="center" prop="leaderName"/>
      <!--      <el-table-column label="科室id" align="center" prop="deptId"/>-->
      <el-table-column label="申请时间" align="center" prop="applyTime" width="180"/>
      <!--      <el-table-column label="创建人" align="center" prop="createBy"/>-->
      <!--      <el-table-column label="创建时间" align="center" prop="createTime"/>-->
      <!--      <el-table-column label="修改人" align="center" prop="updateBy"/>-->
      <!--      <el-table-column label="修改时间" align="center" prop="updateTime"/>-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >审核
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleUpdate(scope.row)"
          >详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 填写审核意见 -->
    <el-dialog :title="title" :visible.sync="open" width="900px">
      <el-form class="scform" ref="form" :model="form" :rules="rules" label-width="120px"
               style="width:100%;display: flex;flex-direction: row;flex-wrap: wrap"
      >
        <el-form-item label="审核意见" prop="auditStatus">
          <!-- 使用 el-radio-group 和 el-radio 组件 -->
          <el-radio-group v-model="form.auditStatus">
            <el-radio label="1">通过</el-radio>
            <el-radio label="2">驳回</el-radio>
          </el-radio-group>
          <!-- 输入框使用 v-if 或 v-show 控制显示 -->
          <el-input v-model="form.reason" :required="radio === '2'" placeholder="请输入通过/驳回原因"></el-input>
        </el-form-item>
      </el-form>
      <div class="sign-canvas">
        <div>电子签名处：</div>
        <sign-canvas style="display: block;" ref="SignCanvas" v-model="sign" @write = "write"/>
        <div style="display: flex;flex-direction: column;justify-content: end;height: 300px;margin-left: 10px;">
          <el-button type="primary" plain @click="canvasClear">重新签名</el-button>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :loading="submitloading">提 交</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 申请单详情对话框 -->
    <el-dialog :title="applyTitle" :visible.sync="applyDialog" width="900px">
      <div class="detail">
        <!--        <div class="itm">审批人： {{ applyInfo.nextAudit }}</div>-->
        <div class="itm">经办人电话： {{ applyInfo.workTel }}</div>
        <div class="itm">送报时间： {{ applyInfo.applyTime }}</div>
      </div>
      <el-table v-loading="loading" :data="applyInfo.details" style="margin-bottom: 20px">
        <el-table-column label="废旧物资名称" align="center" prop="goodsName"/>
        <el-table-column label="规格型号" align="center" prop="goodsSpec"/>
        <el-table-column label="数量" align="center" prop="goodsNum"/>
        <el-table-column label="计量单位" align="center" prop="goodsUnit"/>
        <el-table-column label="重量（千克）" align="center" prop="weight"/>
        <el-table-column label="单价" align="center" prop="unitPrice"/>
        <el-table-column label="提货地点" align="center" prop="place"/>
        <el-table-column label="科室意见" align="center" prop="idea">
          <template slot-scope="scope" >
            <el-input v-model="scope.row.idea" placeholder="请输入科室意见" v-if="roleId == '103'"></el-input>
            <span v-else>{{scope.row.idea}}</span>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark"/>
      </el-table>
      <el-form  v-if="roleId == '103'" class="scform" ref="outForm" :model="outForm" :rules="outRules">
        <el-form-item label="请选择物资分类" prop="fenlei">
          <el-select filterable  value-key="name" reserve-keyword remote v-model="outForm.fenlei" placeholder="物资分类" clearable size="small">
            <el-option
              v-for="dict in typeList"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <DownFile :file="applyInfo.ideaFile" v-if="applyInfo.ideaFile"></DownFile>

      <!--      在这里处理文件上传-->
      <div v-if="roleId == '103'"  style="font-size: 16px;margin-bottom: 10px">{{this.ideaFile}}</div>
      <FileUpload v-if="roleId == '103'" @input="handleSuccess" :fileList = "fileList"/>
      <div class="detail" style="margin-top: 20px;">
        <div class="itmName">
          分管领导： {{ applyInfo.leaderName }}
          <img :src="applyInfo.leaderSign" class="img" v-if="applyInfo.leaderSign"/>
        </div>
        <div class="itmName">
          业务科室负责人： {{ applyInfo.deptLeaderName }}
          <img :src="applyInfo.deptLeaderSign" class="img" v-if="applyInfo.deptLeaderSign"/>
        </div>
        <div class="itmName">
          业务科室分管人员： {{ applyInfo.deptStaffName }}
          <img :src="applyInfo.deptStaffSign" class="img" v-if="applyInfo.deptStaffSign"/>
        </div>
        <div class="itmName">
          车间主任： {{ applyInfo.workLeaderName }}
          <img :src="applyInfo.workLeaderSign" class="img" v-if="applyInfo.workLeaderSign"/>
        </div>
        <div class="itmName">
          经办人： {{ applyInfo.workStaffName }}
          <img :src="applyInfo.workStaffSign" class="img" v-if="applyInfo.workStaffSign"/>
        </div>
        <div class="itmName">
          联系电话： {{ applyInfo.workTel }}
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitApplyForm">审核并签名</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listAudit, applyInfo, delApply, addPost, applyAudit, addApply, auditorList } from '@/api/system/scrap'
import SignCanvas from '../components/signCanvas'
import { listData } from '@/api/system/dict/data'
import Cookies from 'js-cookie'
import DownFile from '../components/downFile'

export default {
  name: 'Post',
  components: { SignCanvas ,DownFile},
  dicts: ['sys_normal_disable'],
  data() {
    return {
      outRules: {
        fenlei: [
          { required: true, message: '分类不能为空', trigger: 'blur' }
        ]
      },
      outForm:{
      },
      typeList:[{
        label:'固定资产拆除报废申请单',
        value:'1'
      },{
        label:'低值易耗品报废申请单',
        value:'2'
      },{
        label:'存货报废申请单',
        value:'3'
      },{
        label:'其他(无需上传照片)',
        value:'4'
      }],
      write:false,
      options:{
        isFullScreen: false,   ////是否全屏手写 [Boolean] 可选
        isFullCover: false, //是否全屏模式下覆盖所有的元素 [Boolean]   可选
        isDpr: false,       //是否使用dpr兼容高分屏 [Boolean] 可选
        lastWriteSpeed: 1,  //书写速度 [Number] 可选
        lastWriteWidth: 2,  //下笔的宽度 [Number] 可选
        lineCap: 'round',   //线条的边缘类型 [butt]平直的边缘 [round]圆形线帽 [square]	正方形线帽
        lineJoin: 'bevel',  //线条交汇时边角的类型  [bevel]创建斜角 [round]创建圆角 [miter]创建尖角。
        canvasWidth: 350, //canvas宽高 [Number] 可选
        canvasHeight: 370,  //高度  [Number] 可选
        isShowBorder: true, //是否显示边框 [可选]
        bgColor: '#fcc', //背景色 [String] 可选
        borderWidth: 1, // 网格线宽度  [Number] 可选
        borderColor: "#ff787f", //网格颜色  [String] 可选
        writeWidth: 5, //基础轨迹宽度  [Number] 可选
        maxWriteWidth: 30, // 写字模式最大线宽  [Number] 可选
        minWriteWidth: 5, // 写字模式最小线宽  [Number] 可选
        writeColor: '#101010', // 轨迹颜色  [String] 可选
        isSign: true, //签名模式 [Boolean] 默认为非签名模式,有线框, 当设置为true的时候没有任何线框
        imgType:'png'   //下载的图片格式  [String] 可选为 jpeg  canvas本是透明背景的
      },
      roleId: Cookies.get('roleId'),
      submitloading: false,
      sign: '',
      applyInfo: {}, // 申请单详情
      applyTitle: '填写报废物资处置申请单',
      pickerOptions: {
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date())
          }
        }, {
          text: '昨天',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24)
            picker.$emit('pick', date)
          }
        }, {
          text: '一周前',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', date)
          }
        }]
      },
      sourceList: [],
      disposeList: [],
      delivererList: [],
      receiverList: [],
      scrapShiftList: [],
      operatorList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      selectedRecords: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 岗位表格数据
      postList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 是否显示弹出层
      applyDialog: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        receiver: undefined,
        deliverer: undefined,
        warehouse: undefined,
        source: undefined,
        goodsName: undefined,
        dispose: undefined
      },
      // 表单参数
      form: {},
      ideaFile: '',
      applyForm: {},
      // 申请单表单校验
      applyRules: {
        nextAudit: [
          { required: true, message: '审批人不能为空', trigger: 'blur' }
        ],
        workTel: [
          { required: true, message: '电话不能为空', trigger: 'blur' }
        ],
        applyTime: [
          { required: true, message: '送报时间不能为空', trigger: 'blur' }
        ]
      },
      auditList: [],
      // 表单校验
      rules: {
        auditStatus: [
          { required: true, message: '审核意见不能为空', trigger: 'blur' }
        ]
      },
      applyId: '',
      fileList:[]
    }
  },
  created() {
    this.getList()
  },
  methods: {
    handleSuccess(fileList) {
      // 文件上传成功的回调处理
      console.log('上传成功', fileList)
      this.ideaFile = fileList
      const array = fileList.split(',')
      this.fileList = array.map(item => {
        return {
          name: item,
          url: item
        }
      })
    },
    getLabelByCode(code, list) {
      console.log(code)
      console.log(list)
      const foundLabel = list.find(item => item.dictValue == code)
      return foundLabel ? foundLabel.dictLabel : '未知'
    },
    /**
     * 清除画板
     */
    canvasClear() {
      this.$refs.SignCanvas.canvasClear()
      this.sign = ''
      this.write = false
      console.log("----------------------------      this.write = false ---------------------------------------------------")
    },
    write(){
      this.write = true
      console.log("----------------------------      this.write = true ---------------------------------------------------")
    },

    /**
     * 保存图片
     */
    saveAsImg() {
      this.sign = this.$refs.SignCanvas.saveAsImg()
      // alert(`image 的base64：${img}`)
    },
    validateField(row) {
        if (this.roleId == '103' && !row.idea) { // 科员必填科室意见
          this.$message.error('科室意见是必填项')
        return false
      } else {
        // 如果有错误状态，这里可以清除错误提示
        return true
      }
    },
    /** 查询岗位列表 */
    getList() {
      this.loading = true
      // 班次车间
      listData({ dictType: 'scrap_shift' }).then(response => {
        this.scrapShiftList = response.rows
      })
      // 交料人
      listData({ dictType: 'deliverer' }).then(response => {
        this.delivererList = response.rows
      })
      // 收料人
      listData({ dictType: 'receiver' }).then(response => {
        this.receiverList = response.rows
      })
      // 撤旧来源
      listData({ dictType: 'deprecition_source' }).then(response => {
        this.sourceList = response.rows
      })
      // 处置方式
      listData({ dictType: 'dispose_way' }).then(response => {
        this.disposeList = response.rows
      })
      listAudit(this.queryParams).then(response => {
        this.postList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 查询审核人列表
    getAuditList() {
      console.log('this.applyId==' + this.applyId)
      auditorList({ applyId: this.applyId }).then(response => {
        this.auditList = response.data
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.applyDialog = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {}
      this.fileList = []
      this.ideaFile = ''
      this.applyForm = {
        nextAudit: undefined,
        workTel: undefined,
        applyTime: undefined
      }
      this.resetForm('outForm')
      this.resetForm('form')
      this.resetForm('applyForm')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      console.log(selection)
      this.ids = selection.map(item => item.applyId)
      this.selectedRecords = selection
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加废旧物资回收入库记录单'
    },
    /** 审核按钮操作 */
    handleUpdate(row) {
      this.reset()
      const applyId = row.applyId
      this.applyId = applyId
      applyInfo({ applyId: applyId }).then(response => {
        this.applyInfo = response.data
        this.applyDialog = true
        this.applyTitle = '审核报废物资处置申请单'
      })
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.sign = this.$refs.SignCanvas.saveAsImg()
          if (!this.sign && this.form.auditStatus == 1) { // 通过且没有签名，驳回可以不签名
            this.$message.error('请填写您的电子签名')
          } else {
            if (this.form.auditStatus == 2 && !this.form.reason) {
              this.$message.error('请填写驳回原因')
              return
            }
            this.submitloading = true
            this.form.sign = this.sign
            this.form.applyId = this.applyId
            if(this.roleId == '103'){
              this.form.ideaFile = this.ideaFile
              this.form.details = this.applyInfo.details
            }
            applyAudit(this.form).then(response => {
              this.$message.success('审核成功')
              this.submitloading = false
              this.open = false
              this.canvasClear()
              this.applyDialog = false
              this.getList()
            }).catch((r) => {
              this.$message.error(r)
              this.submitloading = false
            })
          }
        }
      })
    },
    submitApplyForm: function() {
      for (let i = 0; i < this.applyInfo.details.length; i++) {
        if (!this.validateField(this.applyInfo.details[i])) {
          return false
        }
      }
      if (!this.ideaFile && this.roleId == '103' && this.outForm.fenlei!=4) {
        this.$message.error('请上传附件')
        return
      }
      this.open = true
      this.title = '审核并签名'
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const postIds = row.applyId || this.ids
      this.$modal.confirm('是否确认删除申请单号为"' + postIds + '"的数据项？').then(function() {
        return delApply(postIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/post/export', {
        ...this.queryParams
      }, `post_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
<style scoped lang="scss">
.scform {
  .el-form-item {
    width: 50%;
  }
}

.detail {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;

  .itm {
    width: 50%;
    margin-bottom: 10px;
  }

  .itmName {
    display: flex;
    flex-direction: row;
    align-items: center;
    flex-wrap: nowrap;
    width: 33%;
    margin-top: 20px;
  }

  .img {
    width: 100px;
    height: 50px;
  }
}

.sign-canvas {
  display: flex;
  flex-direction: row;
  width: 100%;
}
</style>
